package com.da.javatest.thread.juc.threadlocal;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author chenlida
 * @date 2020/7/15 19:15
 * @description
 */
public class ThreadLocal1 {
    private static AtomicInteger threadIndex = new AtomicInteger(1);
    //创建处理请求的线程池子
    private static ThreadPoolExecutor disposeRequestExecutor = new ThreadPoolExecutor(3, 3, 60, TimeUnit.SECONDS,
        new LinkedBlockingDeque<>(),
        r -> {
            Thread thread = new Thread(r);
            thread.setName("disposeRequestThread-" + threadIndex.getAndIncrement());
            return thread;
        });

    //记录日志
    public static void log(String msg, String traceId) {
        StackTraceElement stack[] = (new Throwable()).getStackTrace();
        System.out.println("****" + System.currentTimeMillis() + "[traceId:" + traceId + "],[线程:"
            + Thread.currentThread().getName() + "]," + stack[1] + ":" + msg);
    }

    //模拟controller
    public static void controller(List<String> dataList, String traceId) {
        log("接受请求", traceId);
        service(dataList, traceId);
    }

    //模拟service
    public static void service(List<String> dataList, String traceId) {
        log("执行业务", traceId);
        dao(dataList, traceId);
    }

    //模拟dao
    public static void dao(List<String> dataList, String traceId) {
        log("执行数据库操作", traceId);
        //模拟插入数据
        for (String s : dataList) {
            log("插入数据" + s + "成功", traceId);
        }
    }

    public static void main(String[] args) {
        //需要插入的数据
        List<String> dataList = Arrays.asList("数据1", "数据2", "数据3");

        //模拟5个请求
        int requestCount = 5;
        for (int i = 1; i <= requestCount; i++) {
            String traceId = String.valueOf(i);
            disposeRequestExecutor.execute(() -> controller(dataList, traceId));
        }

        disposeRequestExecutor.shutdown();
    }
}
